"""
@Project ：interface_platform 
@File    ：logging_utils.py
@IDE     ：PyCharm 
@Author  ：ZSR
@Date    ：2023/3/20 22:28 
"""

import logging
from logging import handlers
from backend.config import LOG_LEVEL
from backend.config import BASE_DIR


# 定义一个收集日志的方法
def init_logging(logger_name=None, stream=None):
    # 实例化日志器
    logger = logging.getLogger(logger_name)
    # 设置日志等级
    logger.setLevel(LOG_LEVEL)
    filename = BASE_DIR + "/backend/logs/test.log"
    # 设置处理器
    sh = logging.StreamHandler(stream=stream)  # 设置控制台处理器
    fh = logging.handlers.TimedRotatingFileHandler(filename=filename,
                                                   when='h',
                                                   interval=24,
                                                   backupCount=7,
                                                   encoding="utf-8")

    # 设置格式化器
    fmt = "[%(asctime)s %(levelname)s %(threadName)s %(filename)s %(funcName)s %(lineno)d] [%(thread)d] [%(message)s]"
    formatter = logging.Formatter(fmt)

    # 将格式化器添加到处理器
    fh.setFormatter(formatter)
    sh.setFormatter(formatter)
    # 将处理器添加到日志器
    logger.addHandler(fh)
    logger.addHandler(sh)

    return logger
